function streamCall(sid, query, end) {
  const url = localStorage.getItem('url');
  const key = localStorage.getItem('key');
  let q = JSON.parse(query)
  q['stream'] = true;
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${key}`
    },
    body: JSON.stringify(q)
  })
    .then((response) => {

      if (!response.ok) {
        if (response.status === 404) {
          // chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: '404' });
          end('404')
        } else {
          // chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: `${response.status}` });
          end(`${response.status}`)
        }
        return
      }

      // 处理流式响应
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');

      var partial = ""
      var reason = '';
      var obj;

      function readChunk() {
        reader.read().then(({ done, value }) => {
          if (done) {
            // console.log(partial)
            end(partial)
            return
          }

          // 解码并处理每一部分的流式数据
          const chunk = decoder.decode(value, { stream: true });

          // 将流式数据发送到前台页面
          let items = chunk.split("\n\n")
          for (let i = 0; i < items.length; i++) {
            if (!items[i].trim()) {
              continue
            }
            // console.log(items[i].replace(/^data:/, ''));
            try {
              // console.log(items[i])
              obj = JSON.parse(items[i].replace(/^data:/, ''))

              const reason_content = obj['choices'][0]['delta']['reasoning_content'] ?? '';
              const content = obj['choices'][0]['delta']['content'];
              if (reason_content) {
                if (!reason) {
                  chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: "<think>" });
                }
                reason += reason_content
                chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: reason_content });
              }
              else if (content) {
                if (reason && !partial) {
                  chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: "</think>\n" });
                }
                partial += content

                chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: content });
              }
            }
            catch (e) {
              // end(`[chunk.parse] ${e.message}`)
              // end(partial)
              // continue
            }
          }
          readChunk()
        })
        .catch((e) => {
          end(`[ERROR] ${e.message}`)
        })
      }

      readChunk()

    })
    .catch(e => {
      console.log(e.message)
      chrome.runtime.sendMessage({ action: `stream_${sid}`, chunk: e.message });
      end(`[ERROR] ${e.message}`)
    })


}

chrome.runtime.onInstalled.addListener(function () { });

const msgActions = (function () {

  function queryAI(request, sender, sendResponse) {

  }

  function openAITab(request, sender, sendResponse) {
    const model = localStorage.getItem('model').split(',')[0]
    const time = new Date().getTime()
    const sid = `${model}_${time}`

    localStorage.setItem(sid, JSON.stringify([
      { role: 'user', content: request.value }
    ]));
    sendResponse({
      url: chrome.runtime.getURL(`popup.html#${sid}`),
      session: `${model}_${time}`
    })

    return true
  }

  return {
    queryAI: queryAI,
    openAITab: openAITab
  }
})()

function tracWikiUpdate(author, title, content, next) {
  // 定义 API 的 URL 和密钥
  const apiUrl = localStorage.getItem('trac.wiki.api') || 'http://101.43.121.61:5566/tracd/lint/update_wiki';
  const secretKey = localStorage.getItem('trac.wiki.key') || localStorage.getItem('key');

  if(!secretKey){
    next(null)
    return;
  }

  // 定义要提交的 JSON 数据
  const wikiData = {
    title: title,  // Wiki 页面标题
    signature: secretKey,
    content: content,  // Wiki 页面内容
    author: author || 'chrome'   // 提交者名称，默认为 'system'
  };

  // 使用 fetch 发送 POST 请求
  fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Authorization': secretKey,  // 设置 Authorization 头部
      'Content-Type': 'application/json'  // 设置 Content-Type 为 JSON
    },
    body: JSON.stringify(wikiData)  // 将 JSON 数据转换为字符串
  })
  .then(response => {
    if (!response.ok) {
      // 如果响应状态码不是 200-299，抛出错误
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();  // 解析响应为 JSON
  })
  .then(data => {
    // 成功时调用回调函数，并传递返回的 JSON 数据
    next(data);
  })
  .catch(error => {
    // 失败时调用回调函数，并传递 null
    console.error('Error:', error);
    next(null);
  });
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

  switch (request.action) {
    case 'queryAI':
      // return msgActions.queryAI(request, sender, sendResponse); 
      const url = localStorage.getItem('url');
      const key = localStorage.getItem('key');

      if (!url && !key) {
        sendResponse({ content: "没有配置API" })
        return
      }

      if (request.stream) {
        console.log(`[${request.stream}] ready to stream call`)
        // console.log(JSON.stringify(request))
        streamCall(request.stream, request.query, (answer) => {
          try{
            const query = JSON.parse(request.query)
            const model = query.model
            let messages = query.messages
            if(answer && answer.length > 100 && messages.length == 1 && messages[0]['content']){
              tracWikiUpdate(model, messages[0]['content'], answer, (json) => {
                console.log(JSON.stringify(json))
              })
            }
            // JSON.stringify(this.chatHistory)
            // let history = JSON.parse(localStorage.getItem(request.stream) || '[]');
            // const mlen = history.length
            messages.push({'role': 'assistant', 'content': answer})
            localStorage.setItem(request.stream, JSON.stringify(messages))
          }catch(e){
            console.log(e.message)
          }

          sendResponse({ content: answer })
        })

      } else {
        fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${key}`
          },
          body: request.query
        })
          .then(response => response.json())
          .then(data => {
            sendResponse({
              content: data.choices[0]['message']['content']
            })
          })
          .catch(error => {
            sendResponse({
              content: `error: ${error}`
            })
          })
      }
      break;
    case 'openAITab':
      const model = localStorage.getItem('model').split(',')[0]
      const time = new Date().getTime()
      const sid = `${model}_${time}`

      localStorage.setItem(sid, JSON.stringify([
        { role: 'user', content: request.value }
      ]));
      sendResponse({
        url: chrome.runtime.getURL(`popup.html#${sid}`),
        session: `${model}_${time}`
      })
      break;
    case 'wiki':
      tracWikiUpdate(request.title, request.content, (json) => {
        console.log(`[${title}] ${JSON.stringify(json)}`)
      })
      break;
    default:
      console.log(`unknown action[${request.action}]`)
  }

  return true;
});

